package com.shuwen.gcdj.service.statistic;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuwen.gcdj.bean.Home.request.HomeStatusReq;
import com.shuwen.gcdj.bean.Home.response.HomeAnimationSensorResp;
import com.shuwen.gcdj.bean.Home.response.HomeStatusSensorResp;
import com.shuwen.gcdj.bean.Home.response.OverlookingHomeResp;
import com.shuwen.gcdj.bean.basicsEquitment.response.EquipmentExternalLinksResp;
import com.shuwen.gcdj.bean.basicsEquitment.response.EquipmentResp;
import com.shuwen.gcdj.bean.conditionMonitoring.request.StressMetersReq;
import com.shuwen.gcdj.bean.conditionMonitoring.response.TDSensorCodeDataAllResp;
import com.shuwen.gcdj.bean.sysDictionary.request.SysDictionaryReq;
import com.shuwen.gcdj.bean.sysDictionary.response.SysDictionaryResp;
import com.shuwen.gcdj.bean.workingConditions.response.StatisticPlcMetersResp;
import com.shuwen.gcdj.bean.workingConditions.response.StatisticTDConditionResp;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.common.util.FieldUtil;
import com.shuwen.gcdj.entity.SysDictionary;
import com.shuwen.gcdj.entity.basics.BasicsEquipment;
import com.shuwen.gcdj.mapper.mysql.basics.BasicsEquipmentMapper;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import com.shuwen.gcdj.mapper.tdengine.Statistic.StatisticPlcSensorMapper;
import com.shuwen.gcdj.mapper.tdengine.Statistic.StatisticStressMetersMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 首页动画
 *
 * @author XYC
 */

@Service
@AllArgsConstructor
@Slf4j
public class HomeService {

    private final SysDictionaryMapper sysDictionaryMapper;

    private final StatisticStressMetersMapper statisticStressMetersMapper;

    private final StatisticPlcSensorMapper statisticPlcSensorMapper;

    private final BasicsEquipmentMapper basicsEquipmentMapper;


    public SysDictionaryResp sysDictionaryResp(HomeStatusReq req) {
        //当时间为空时，获取当前时间
        req.setTs(req.getTs() == null ? LocalDateTime.now() : req.getTs());
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.SENSOR_STATISTICS);
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> sysDictionaryRespList = sysDictionaryMapper.getList(sysDictionaryReq);
        //首页应变传感器查询数量与间隔
        return sysDictionaryRespList.stream().filter(sysDictionaryResp -> sysDictionaryResp.getValue().equals(Constants.HOME_STRAIN)).findFirst().orElse(new SysDictionaryResp());
    }

    public List<HomeStatusSensorResp> homeStatusSensorResponses(List<SysDictionaryResp> sensors
            , StressMetersReq stressMetersReq, List<HomeStatusSensorResp> homeStatusSensorList, String sensorType) {
        //获取振动传感器
        List<SysDictionaryResp> sysDictionaries = new ArrayList<>();
        if (sensorType.equals(Constants.VIBRATING_MONITOR)) {
            SysDictionaryReq dictionaryReq = new SysDictionaryReq();
            dictionaryReq.setParentCode(Constants.SENSOR_TABLES);
            dictionaryReq.setOperateObject(stressMetersReq.getEquipmentCode());
            dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
            sysDictionaries = sysDictionaryMapper.getList(dictionaryReq);
        }
        for (SysDictionaryResp resp : sensors) {
            //查询主梁传感器数据
            HomeStatusSensorResp homeStatusSensorResp = new HomeStatusSensorResp();
            List<String> streets = new ArrayList<>();
            List<String> datetime = new ArrayList<>();
            if (sensorType.equals(Constants.STRAIN_MONITOR)) {
                stressMetersReq.setSensorCode(resp.getCode() + ",ts");
                DateUtil.format(DateUtil.date(), DatePattern.PURE_TIME_PATTERN);
                List<TDSensorCodeDataAllResp> stressMeters = statisticStressMetersMapper.getStrainListA(stressMetersReq).stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
                datetime = stressMeters.stream().map(stressMetersResp -> DateUtil.format(stressMetersResp.getTs(), DatePattern.NORM_TIME_PATTERN)).collect(Collectors.toList());
                streets = FieldUtil.usersBlankNum(resp.getCode(), TDSensorCodeDataAllResp.class, stressMeters);
            } else if (sensorType.equals(Constants.VIBRATING_MONITOR)) {
                SysDictionaryResp dictionary = sysDictionaries.stream().filter(dictionaries -> dictionaries.getCode().equals(resp.getCode())).findFirst().orElse(null);
                stressMetersReq.setSensorCode(resp.getCode() + ",ts");
                assert dictionary != null;
                stressMetersReq.setTableName(dictionary.getName());
                List<TDSensorCodeDataAllResp> accelerations = statisticStressMetersMapper.getVibrationListA(stressMetersReq).stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
                datetime = accelerations.stream().map(accelerationMetersResp -> DateUtil.format(accelerationMetersResp.getTs(), DatePattern.NORM_TIME_PATTERN)).collect(Collectors.toList());
                streets = FieldUtil.usersBlankNum(resp.getCode(), TDSensorCodeDataAllResp.class, accelerations);
            }
            //拿取时间
            List<String> dateTimes = datetime.stream().map(String::valueOf).collect(Collectors.toList());
            homeStatusSensorResp.setSensorPosition(resp.getRemark());
            homeStatusSensorResp.setDateTimeName(dateTimes);
            homeStatusSensorResp.setNumericValue(streets);
            homeStatusSensorList.add(homeStatusSensorResp);
        }
        return homeStatusSensorList;
    }

    //小车内的起升机构数据计算
    public List<HomeAnimationSensorResp> homeAnimationSensorRespList(List<SysDictionaryResp> sensors, List<SysDictionaryResp> sensorsWeight
            , TDSensorCodeDataAllResp plcMeters, SysDictionaryResp lengthData, List<SysDictionaryResp> algorithms, String trolley) {
        //上下小车
        List<HomeAnimationSensorResp> animationSensorRespList = new ArrayList<>();
        //位置
        List<SysDictionaryResp> sysDictionaryRespList = sensors.stream().filter(sysDictionaryResp -> sysDictionaryResp.getRemark().contains(trolley)).collect(Collectors.toList());
        //重量
        List<SysDictionaryResp> sensorsWeightsData = sensorsWeight.stream().filter(sysDictionaryResp -> sysDictionaryResp.getRemark().contains(trolley)).collect(Collectors.toList());
        sysDictionaryRespList.addAll(sensorsWeightsData);
        List<String> trolleyList = sysDictionaryRespList.stream().map(SysDictionaryResp::getRemark).distinct().collect(Collectors.toList());
        for (String data : trolleyList) {
            HomeAnimationSensorResp homeAnimationSensorResp = new HomeAnimationSensorResp();
            //查询起升机构传感器数据
            //位置
            SysDictionaryResp position = sysDictionaryRespList.stream().filter(sysDictionaryResp -> sysDictionaryResp.getRemark().equals(data)).findFirst().orElse(new SysDictionaryResp());
            String lifting = FieldUtil.usersBlankNum(position.getCode(), TDSensorCodeDataAllResp.class, plcMeters);

            //重量
            SysDictionaryResp weight = sensorsWeightsData.stream().filter(sysDictionaryResp -> sysDictionaryResp.getRemark().equals(data)).findFirst().orElse(new SysDictionaryResp());
            String weightData = FieldUtil.usersBlankNum(weight.getCode(), TDSensorCodeDataAllResp.class, plcMeters);

            BigDecimal lengths = new BigDecimal(lengthData.getRemark());
            BigDecimal bigDecimal = BigDecimal.valueOf(0);


            //起升位置 1，2 ，3 分别 /10 ，/11，/12
            switch (data) {
                case Constants.ONTHETROLLEY_1:
                case Constants.OFFTHETROLLEY_1: {
                    SysDictionaryResp dictionary = algorithms.stream().filter(sysDictionaryResp -> sysDictionaryResp.getCode().contains(Constants.LIFTING_A)).findFirst().orElse(null);
                    String formula = dictionary != null ? dictionary.getRemark() : Constants.COMPUTE;
                    String str = lifting + formula;
                    bigDecimal = BigDecimal.valueOf(WorkingConditionsService.eval(str));
                    break;
                }
                case Constants.ONTHETROLLEY_2:
                case Constants.OFFTHETROLLEY_2: {
                    //计算位置
                    SysDictionaryResp dictionary = algorithms.stream().filter(sysDictionaryResp -> sysDictionaryResp.getCode().contains(Constants.LIFTING_B)).findFirst().orElse(null);
                    String formula = dictionary != null ? dictionary.getRemark() : Constants.COMPUTE;
                    String str = lifting + formula;
                    bigDecimal = BigDecimal.valueOf(WorkingConditionsService.eval(str));
                    break;
                }
                case Constants.ONTHETROLLEY_3:
                case Constants.OFFTHETROLLEY_3: {
                    //计算位置
                    SysDictionaryResp dictionary = algorithms.stream().filter(dictionaryResp -> dictionaryResp.getCode().contains(Constants.LIFTING_C)).findFirst().orElse(null);
                    String formula = dictionary != null ? dictionary.getRemark() : Constants.COMPUTE;
                    String str = lifting + formula;
                    bigDecimal = BigDecimal.valueOf(WorkingConditionsService.eval(str));
                    break;
                }
            }
            //载荷公式 /10
            SysDictionaryResp loadResp = algorithms.stream().filter(x -> x.getCode().contains(Constants.LOAD)).findFirst().orElse(null);
            String load = loadResp != null ? loadResp.getRemark() : Constants.OUTCOME;
            String strLoad = weightData + load;
            //计算载荷
            BigDecimal loadArithmetic = BigDecimal.valueOf(WorkingConditionsService.eval(strLoad));
            //计算在总长度占比起升
            BigDecimal measure = bigDecimal.divide(lengths, 2, RoundingMode.HALF_UP);
            String weightValue = weightData == null ? Constants.OUTCOME : String.valueOf(loadArithmetic.setScale(2, RoundingMode.HALF_UP));
            homeAnimationSensorResp.setSensorName(position.getName());
            homeAnimationSensorResp.setMeasure(String.valueOf(String.format("%.2f", bigDecimal)));
            homeAnimationSensorResp.setPercentage(String.valueOf(measure));
            homeAnimationSensorResp.setSensorCode(position.getCode());
            homeAnimationSensorResp.setValue(position.getValue());
            homeAnimationSensorResp.setWeight(weightValue);
            homeAnimationSensorResp.setHeight(String.valueOf(String.format("%.2f", bigDecimal)));
            animationSensorRespList.add(homeAnimationSensorResp);
        }
        return animationSensorRespList;
    }

    //查询应变传感器
    public CommonResult<List<HomeStatusSensorResp>> getStrainAsync(HomeStatusReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        List<HomeStatusSensorResp> homeStatusSensorList = new ArrayList<>();
        //当时间为空时，获取当前时间
        req.setTs(req.getTs() == null ? LocalDateTime.now() : req.getTs());
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        //首页应变传感器查询数量与间隔
        SysDictionaryResp dictionaryResp = sysDictionaryResp(req);
        //获取查询时间间隔（分）
        int number = dictionaryResp.getCode() != null ? Integer.parseInt(dictionaryResp.getCode()) : Constants.TIME_DIFFERENCE;
        //获取查询数量
        int limit = dictionaryResp.getName() != null ? Integer.parseInt(dictionaryResp.getName()) : Constants.NUMBER_OF_QUERIES;
        //获取Td超级表名称
        sysDictionaryReq.setParentCode(Constants.EQUIPMENT_CODE_TDSTABLE);
        sysDictionaryReq.setOperateObject(req.getEquipmentCode());
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> dictionaryRespList = sysDictionaryMapper.getList(sysDictionaryReq);
        SysDictionaryResp tableName = dictionaryRespList.stream().filter(sysDictionaryResp -> sysDictionaryResp.getCode().contains(Constants.GANTRY_CRANE_STRAIN)).findFirst().orElse(new SysDictionaryResp());
        //查询设备对象
        SysDictionaryReq equipment = new SysDictionaryReq();
        equipment.setParentCode(Constants.CRANE_EQUIPMENT_OBJECT);
        equipment.setCode(req.getEquipmentCode());
        equipment.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        SysDictionaryResp equipmentObject = sysDictionaryMapper.getSingle(equipment);
        //获取传感器编码
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setParentCode(Constants.STATISTICS_STRAIN_REAL_TIME_SENSOR);
        dictionaryReq.setOperateObject(equipmentObject.getCode());
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> sensors = sysDictionaryMapper.getList(dictionaryReq);
        if (CollectionUtils.isEmpty(sensors)) {
            return CommonResult.success(homeStatusSensorList);
        }
        //查询开始时间
        LocalDateTime startDate = req.getTs().minusMinutes(number);
        //查询结束时间
        String endDate = req.getTs().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        StressMetersReq stressMetersReq = new StressMetersReq();
        stressMetersReq.setLimit(limit);
        stressMetersReq.setTableName(tableName.getCode());
        stressMetersReq.setStartTime(startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        stressMetersReq.setEndDateTime(endDate);
        stressMetersReq.setEquipmentCode(req.getEquipmentCode());
        return CommonResult.success(homeStatusSensorResponses(sensors, stressMetersReq, homeStatusSensorList, Constants.STRAIN_MONITOR));
    }


    //振动
    public CommonResult<List<HomeStatusSensorResp>> getVibrationRealTimeDataSensorAsync(HomeStatusReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        List<HomeStatusSensorResp> homeStatusSensorResps = new ArrayList<>();
        //当时间为空时，获取当前时间
        req.setTs(req.getTs() == null ? LocalDateTime.now() : req.getTs());
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        //首页应变传感器查询数量与间隔
        StressMetersReq meteReq = new StressMetersReq();
        //首页应变传感器查询数量与间隔
        SysDictionaryResp dictionaryResp = sysDictionaryResp(req);
        //获取查询时间间隔（分）
        int number = dictionaryResp.getCode() != null ? Integer.parseInt(dictionaryResp.getCode()) : Constants.TIME_DIFFERENCE;
        //获取查询数量
        int limit = dictionaryResp.getName() != null ? Integer.parseInt(dictionaryResp.getName()) : Constants.NUMBER_OF_QUERIES;
        //获取Td超级表名称
        dictionaryReq.setParentCode(Constants.EQUIPMENT_CODE_TDSTABLE);
        dictionaryReq.setOperateObject(req.getEquipmentCode());
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> sysDictionaries = sysDictionaryMapper.getList(dictionaryReq);
        SysDictionaryResp tableName = sysDictionaries.stream().filter(x -> x.getCode().contains(Constants.VIBRATING_MONITOR)).findFirst().orElse(new SysDictionaryResp());
        //查询设备对象
        SysDictionaryReq equipment = new SysDictionaryReq();
        equipment.setParentCode(Constants.CRANE_EQUIPMENT_OBJECT);
        equipment.setCode(req.getEquipmentCode());
        equipment.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        SysDictionaryResp equipmentObject = sysDictionaryMapper.getSingle(equipment);
        //获取传感器编码
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.STATISTICS_VIBRATION_REAL_TIME_DATA_SENSOR);
        sysDictionaryReq.setOperateObject(equipmentObject.getCode());
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> sensors = sysDictionaryMapper.getList(sysDictionaryReq);
        if (CollectionUtils.isEmpty(sensors)) {
            return CommonResult.success(homeStatusSensorResps);
        }
        //查询开始时间
        LocalDateTime startDate = req.getTs().minusMinutes(number);
        //查询结束时间
        String endDate = req.getTs().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        meteReq.setLimit(limit);
        meteReq.setStartTime(startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        meteReq.setEndDateTime(endDate);
        meteReq.setEquipmentCode(req.getEquipmentCode());
        return CommonResult.success(homeStatusSensorResponses(sensors, meteReq, homeStatusSensorResps, Constants.VIBRATING_MONITOR));
    }


    //plc动画
    public CommonResult<List<HomeAnimationSensorResp>> getHomeAnimationSensorAsync(HomeStatusReq req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备不存在");
        }
        List<HomeAnimationSensorResp> result = new ArrayList<>();
        StatisticTDConditionResp conditionResp = new StatisticTDConditionResp();
        //判断日期是否为空没有就获取当前日期
        req.setTs(req.getTs() == null ? LocalDateTime.now() : req.getTs());
        //获取设备
        BasicsEquipment equipmentData = basicsEquipmentMapper.selectOne(
                new QueryWrapper<BasicsEquipment>()
                        .lambda()
                        .eq(BasicsEquipment::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsEquipment::getCode, req.getEquipmentCode()));
        //获取首页起升机构传感器位置编码
        List<SysDictionaryResp> sensors = sysDictionaryRespList(Constants.HOME_ANIMATION_POSITION_SENSOR, req.getEquipmentCode());
        //获取首页传感器重量编码
        List<SysDictionaryResp> sensorsWeight = sysDictionaryRespList(Constants.HOME_ANIMATION_WEIGHT, req.getEquipmentCode());
        //获取设备总长
        SysDictionaryReq dic = new SysDictionaryReq();
        dic.setParentCode(Constants.DEVICE_AREA_LENGTH);
        dic.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> deviceLength = sysDictionaryMapper.getList(dic);
        //超级表
        List<SysDictionaryResp> superTables = sysDictionaryRespList(Constants.EQUIPMENT_CODE_TDSTABLE, req.getEquipmentCode());
        //小车类型
        List<SysDictionaryResp> trolleyType = sysDictionaryRespList(Constants.CRANE_TROLLEY_TYPE, req.getEquipmentCode());
        //plc超级表数据
        SysDictionaryResp superTable = superTables.stream().filter(x -> x.getCode().contains(Constants.GANTRY_CRANE_PLC)).findFirst().orElse(new SysDictionaryResp());
        //获取Plc算法
        List<SysDictionaryResp> algorithms = sysDictionaryRespList(Constants.SENSOR_ALGORITHM, req.getEquipmentCode());
        //设备整机位置传感器
        SysDictionaryReq position = new SysDictionaryReq();
        position.setParentCode(Constants.STATISTICS_EQUIPMENT_POSITION);
        position.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> positions = sysDictionaryMapper.getList(position);
        SysDictionaryResp positionResp = positions.stream().filter(x -> x.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());
        //传感器上小车位置
        SysDictionaryReq topPosition = new SysDictionaryReq();
        topPosition.setParentCode(Constants.STATISTICS_EQUIPMENT_TOP_POSITION);
        topPosition.setOperateObject(req.getEquipmentCode());
        topPosition.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        SysDictionaryResp topPositions = sysDictionaryMapper.getSingle(topPosition);
        //传感器下小车位置
        SysDictionaryReq underPosition = new SysDictionaryReq();
        underPosition.setParentCode(Constants.STATISTICS_EQUIPMENT_UNDER_POSITIONS);
        underPosition.setOperateObject(req.getEquipmentCode());
        underPosition.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        SysDictionaryResp underPositions = sysDictionaryMapper.getSingle(underPosition);
        //取出机构中传感器codes
        List<String> sensorCodes = sensors.stream().map(SysDictionaryResp::getCode).collect(Collectors.toList());
        List<String> sensorWeightCodes = sensorsWeight.stream().map(SysDictionaryResp::getCode).collect(Collectors.toList());
        sensorCodes.addAll(sensorWeightCodes);
        sensorCodes.add(topPositions.getRemark());
        sensorCodes.add(underPositions.getRemark());
        //开始结束时间
        String endTime = req.getTs().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        conditionResp.setSensorCode(String.join(",", sensorCodes));
        conditionResp.setTableName(superTable.getCode());
        conditionResp.setStartTime(req.getTs().minusSeconds(Constants.TIME_DIFFERENCE).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        conditionResp.setEndDateTime(endTime);
        conditionResp.setEqupmentCode(req.getEquipmentCode());
        //查询plc数据
        TDSensorCodeDataAllResp plcMeters = statisticPlcSensorMapper.getResultA(conditionResp);
        plcMeters = plcMeters == null ? new TDSensorCodeDataAllResp() : plcMeters;
        //小车距离
        SysDictionaryResp underLength = deviceLength.stream().filter(sysDictionaryResp -> sysDictionaryResp.getCode().contains(Constants.TROLLEY) && sysDictionaryResp.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());

        //起升机构高度
        SysDictionaryResp lengthData = deviceLength.stream().filter(sysDictionaryResp -> sysDictionaryResp.getCode().contains(Constants.LIFTING) && sysDictionaryResp.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());

        //上小车位置
        //位置值
        String topMeasure = FieldUtil.usersBlankNum(topPositions.getRemark(), TDSensorCodeDataAllResp.class, plcMeters);
        double topTrolleyLength = Double.parseDouble(underLength.getRemark() == null ? Constants.OUTCOME : underLength.getRemark());
        HomeAnimationSensorResp topHomeAnimationSensor = new HomeAnimationSensorResp();
        topHomeAnimationSensor.setMeasure(String.valueOf(topMeasure != null ? String.format("%.2f", Double.parseDouble(topMeasure)) : 0));
        topHomeAnimationSensor.setPercentage(String.format("%.2f", topMeasure != null ? (((Double.parseDouble(topMeasure)) / Constants.CHUNK) / topTrolleyLength) : Constants.ZERO));
        topHomeAnimationSensor.setSensorCode(topPositions.getRemark());
        topHomeAnimationSensor.setSensorName(!CollectionUtils.isEmpty(trolleyType) ? trolleyType.stream().filter(trolley -> trolley.getCode().equals(Constants.ONTHETROLLEY)).findFirst().orElse(new SysDictionaryResp()).getName() : "");
        topHomeAnimationSensor.setIsOnline(topMeasure != null);
        topHomeAnimationSensor.setValue(Constants.TROLLEY_NAME_ABOVE_VALUE);

        //下小车位置
        //位置值
        String underMeasure = FieldUtil.usersBlankNum(underPositions.getRemark(), TDSensorCodeDataAllResp.class, plcMeters);
        HomeAnimationSensorResp underHomeAnimationSensor = new HomeAnimationSensorResp();
        underHomeAnimationSensor.setMeasure(String.valueOf(underMeasure != null ? String.format("%.2f", Double.parseDouble(underMeasure)) : 0));
        underHomeAnimationSensor.setPercentage(String.format("%.2f", underMeasure != null ? ((Double.parseDouble(underMeasure) / Constants.CHUNK) / topTrolleyLength) : Constants.ZERO));
        underHomeAnimationSensor.setSensorCode(underPositions.getRemark());
        underHomeAnimationSensor.setSensorName(!CollectionUtils.isEmpty(trolleyType) ? trolleyType.stream().filter(trolley -> trolley.getCode().equals(Constants.OFFTHETROLLEY)).findFirst().orElse(new SysDictionaryResp()).getName() : "");
        underHomeAnimationSensor.setIsOnline(underMeasure != null);
        underHomeAnimationSensor.setValue(Constants.TROLLEY_NAME_UNDER_VALUE);

        //上小车
        topHomeAnimationSensor.setTrolleyLifting(homeAnimationSensorRespList(sensors, sensorsWeight, plcMeters, lengthData, algorithms, Constants.ONTHETROLLEY));
        //下小车
        underHomeAnimationSensor.setTrolleyLifting(homeAnimationSensorRespList(sensors, sensorsWeight, plcMeters, lengthData, algorithms, Constants.OFFTHETROLLEY));


        StatisticTDConditionResp statisticTDConditionResp = new StatisticTDConditionResp();
        statisticTDConditionResp.setTableName(positionResp.getCode());
        statisticTDConditionResp.setSensorCode(positionResp.getRemark());
        statisticTDConditionResp.setStartTime(req.getTs().minusSeconds(Constants.TIME_DIFFERENCE).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        statisticTDConditionResp.setEndDateTime(endTime);
        statisticTDConditionResp.setEqupmentCode(equipmentData.getCode());
        statisticTDConditionResp.setLimit(Constants.NUMBER_OF_QUERIES);

        Arrays.asList(positionResp.getRemark().split(","));
        //查询plc
        TDSensorCodeDataAllResp positionPlc = statisticPlcSensorMapper.getResultA(statisticTDConditionResp);
        positionPlc = positionPlc == null ? new TDSensorCodeDataAllResp() : positionPlc;
        String measures = FieldUtil.usersBlankNum(positionResp.getRemark(), TDSensorCodeDataAllResp.class, positionPlc);
        SysDictionaryResp regionLength = deviceLength.stream().filter(dev -> dev.getOperateObject().equals(equipmentData.getCode()) && dev.getCode().equals(Constants.DEVICE_AREA_DISTANCE)).findFirst().orElse(new SysDictionaryResp());
        Double length = Double.valueOf(regionLength.getRemark() == null ? Constants.OUTCOME : regionLength.getRemark());
        String location = String.format("%.2f", measures != null ? (Double.parseDouble(measures) / length) * 100 : Constants.ZERO);
        topHomeAnimationSensor.setCartLocation(location);
        underHomeAnimationSensor.setCartLocation(location);
        result.add(topHomeAnimationSensor);
        result.add(underHomeAnimationSensor);
        return CommonResult.success(result);
    }

    //起升机构总高度
    private SysDictionaryResp getSysDictionaryResp(List<SysDictionaryResp> deviceLength, BasicsEquipment equipmentData, SysDictionaryResp underLength) {
        underLength = deviceLength.stream().filter(device -> device.getCode().equals(Constants.TROLLEY) && device.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());
        return underLength;
    }

    public List<SysDictionaryResp> sysDictionaryRespList(String parentCode, String operateObject) {
        SysDictionaryReq superTableReq = new SysDictionaryReq();
        superTableReq.setParentCode(parentCode);
        superTableReq.setOperateObject(operateObject);
        superTableReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        return sysDictionaryMapper.getList(superTableReq);
    }


    //查询俯视首页动画（所有设备）
//    public List<OverlookingHomeResp> getOverlookingHome() {
//        List<OverlookingHomeResp> result = new ArrayList<>();
//        //获取当前时间
//        LocalDateTime ts = LocalDateTime.now();
//        //超级表
///*        SysDictionaryReq superTableReq = new SysDictionaryReq();
//        superTableReq.setParentCode(Constants.EQUIPMENT_CODE_TDSTABLE);
//        superTableReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
//        List<SysDictionaryResp> superTables = sysDictionaryMapper.getList(superTableReq);*/
//        //传感器总重
//        SysDictionaryReq sensorWeight = new SysDictionaryReq();
//        sensorWeight.setParentCode(Constants.STATISTICS_EQUIPMENT_WEIGHT);
//        sensorWeight.setState(Constants.SYS_DICTIONARY_STATE_VALID);
//        List<SysDictionaryResp> sensorWeights = sysDictionaryMapper.getList(sensorWeight);
//        //传感器大车位置
//        SysDictionaryReq position = new SysDictionaryReq();
//        position.setParentCode(Constants.STATISTICS_EQUIPMENT_POSITION);
//        position.setState(Constants.SYS_DICTIONARY_STATE_VALID);
//        List<SysDictionaryResp> positions = sysDictionaryMapper.getList(position);
//        //传感器上小车位置
//        SysDictionaryReq topPosition = new SysDictionaryReq();
//        topPosition.setParentCode(Constants.STATISTICS_EQUIPMENT_TOP_POSITION);
//        topPosition.setState(Constants.SYS_DICTIONARY_STATE_VALID);
//        List<SysDictionaryResp> topPositions = sysDictionaryMapper.getList(topPosition);
//        //传感器下小车位置
//        SysDictionaryReq underPosition = new SysDictionaryReq();
//        underPosition.setParentCode(Constants.STATISTICS_EQUIPMENT_UNDER_POSITIONS);
//        List<SysDictionaryResp> underPositions = sysDictionaryMapper.getList(underPosition);
//        //查询设备对象
//        SysDictionaryReq equipment = new SysDictionaryReq();
//        equipment.setParentCode(Constants.CRANE_EQUIPMENT_OBJECT);
//        equipment.setState(Constants.SYS_DICTIONARY_STATE_VALID);
//        List<SysDictionaryResp> equipmentObjects = sysDictionaryMapper.getList(equipment);
//        //获取所有设备
//        List<BasicsEquipment> equipments = basicsEquipmentMapper.selectList(
//                new QueryWrapper<BasicsEquipment>()
//                        .lambda()
//                        .eq(BasicsEquipment::getIsDelete, Constants.IS_DELETE_NORMAL));
//        SysDictionaryReq statistics = new SysDictionaryReq();
//        statistics.setParentCode(Constants.SENSOR_STATISTICS);
//        statistics.setState(Constants.SYS_DICTIONARY_STATE_VALID);
//        List<SysDictionaryResp> datas = sysDictionaryMapper.getList(statistics);
//        //获取设备总长
//        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
//        dictionaryReq.setParentCode(Constants.DEVICE_AREA_LENGTH);
//        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
//        List<SysDictionaryResp> deviceLength = sysDictionaryMapper.getList(dictionaryReq);
//        //首页应变传感器查询数量与间隔
//        SysDictionaryResp dictionaryResp = datas.stream().filter(x -> x.getValue().equals(Constants.HOME_OVERLOOKING)).findFirst().orElse(new SysDictionaryResp());
//        //获取查询时间间隔（秒）
//        int number = dictionaryResp.getCode() != null ? Integer.parseInt(dictionaryResp.getCode()) : Constants.TIME_DIFFERENCE;
//        //获取查询数量
//        int limit = dictionaryResp.getName() != null ? Integer.parseInt(dictionaryResp.getName()) : Constants.NUMBER_OF_QUERIES;
//        //查询开始时间
//        String startDate = LocalDateTime.now().minusSeconds(number).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        //查询结束时间
//        String endDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        for (BasicsEquipment equipmentData : equipments) {
//
//            result.add(overlookingHomeResp(sensorWeights, positions, topPositions
//                    , underPositions, equipmentObjects, deviceLength, equipmentData
//                    , startDate, endDate, limit));
//        }
//        return result;
//    }

    //每个设备的上下小车起升机构进行计算
//    public OverlookingHomeResp overlookingHomeResp(List<SysDictionaryResp> sensorWeights, List<SysDictionaryResp> positions, List<SysDictionaryResp> topPositions
//            , List<SysDictionaryResp> underPositions, List<SysDictionaryResp> equipmentObjects, List<SysDictionaryResp> deviceLength, BasicsEquipment equipmentData
//            , String startDate, String endDate, int limit) {
//        StatisticTDConditionResp statisticTDConditionResp = new StatisticTDConditionResp();
//        OverlookingHomeResp overlookingHomeResp = new OverlookingHomeResp();
//        //获取当前总重传感器
//        SysDictionaryResp weightsResp = sensorWeights.stream().filter(x -> x.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());
//        //获取当前位置传感器
//        SysDictionaryResp positionResp = positions.stream().filter(x -> x.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());
//        //获取当前上小位置传感器
//        SysDictionaryResp topResp = topPositions.stream().filter(x -> x.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());
//        //获取当前下小位置传感器
//        SysDictionaryResp underResp = underPositions.stream().filter(x -> x.getOperateObject().equals(equipmentData.getCode())).findFirst().orElse(new SysDictionaryResp());
//        //获取设备对象
//        SysDictionaryResp equipmentObject = equipmentObjects.stream().filter(x -> x.getCode().equals(equipmentData.getCode())).findFirst().orElse(null);
//        //设备区域总长度
//        SysDictionaryResp regionLength = deviceLength.stream().filter(x -> x.getCode().equals(Constants.DEVICE_AREA_DISTANCE)).findFirst().orElse(new SysDictionaryResp());
//        SysDictionaryResp underLength = null;
//        underLength = getSysDictionaryResp(deviceLength, equipmentData, underLength);
//        statisticTDConditionResp.setTableName(weightsResp.getCode());
//        statisticTDConditionResp.setSensorCodes(weightsResp.getRemark() != null ? Arrays.asList(weightsResp.getRemark().split(",")) : new ArrayList<>());
//        statisticTDConditionResp.setStartTime(startDate);
//        statisticTDConditionResp.setEndDateTime(endDate);
//        statisticTDConditionResp.setEqupmentCode(equipmentData.getCode());
//        statisticTDConditionResp.setLimit(limit);
//        //查询plc
//        List<StatisticPlcMetersResp> weightgetPlc = statisticPlcSensorMapper.getResult(statisticTDConditionResp);
//        //当前总重
//        List<Double> weightMeasures = weightgetPlc.stream().filter(x -> x.getEquipmentcode().equals(equipmentData.getCode())).map(StatisticPlcMetersResp::getMeasure).collect(Collectors.toList());
//        overlookingHomeResp.setCurrentWeight(String.valueOf(weightMeasures.stream().mapToDouble(Double::doubleValue).sum()));
//        statisticTDConditionResp.setTableName(positionResp.getCode());
//        statisticTDConditionResp.setSensorCodes(Arrays.asList(positionResp.getRemark().split(",")));
//        statisticTDConditionResp.setStartTime(startDate);
//        statisticTDConditionResp.setEndDateTime(endDate);
//        statisticTDConditionResp.setEqupmentCode(equipmentData.getCode());
//        statisticTDConditionResp.setLimit(limit);
//        //查询plc
//        List<StatisticPlcMetersResp> positionPlc = statisticPlcSensorMapper.getResult(statisticTDConditionResp);
//        StatisticPlcMetersResp positionMeasures = positionPlc.stream().filter(x -> x.getEquipmentcode().equals(equipmentData.getCode())).findFirst().orElse(new StatisticPlcMetersResp());
//        Double length = Double.valueOf(regionLength.getRemark() == null ? Constants.OUTCOME : regionLength.getRemark());
//        //大车位置
//        overlookingHomeResp.setPosition(String.format("%.2f", positionMeasures.getMeasure() != null ? (positionMeasures.getMeasure() / length) * 100 : Constants.ZERO));
//        overlookingHomeResp.setCurrentPosition(String.valueOf(positionMeasures.getMeasure() != null ? positionMeasures.getMeasure() : Constants.ZERO));
//        //上小车
//        statisticTDConditionResp.setTableName(topResp.getCode());
//        statisticTDConditionResp.setSensorCodes(Arrays.asList(topResp.getRemark().split(",")));
//        statisticTDConditionResp.setStartTime(startDate);
//        statisticTDConditionResp.setEndDateTime(endDate);
//        statisticTDConditionResp.setEqupmentCode(equipmentData.getCode());
//        statisticTDConditionResp.setLimit(limit);
//        //查询plc
//        List<StatisticPlcMetersResp> topPositionsPlc = statisticPlcSensorMapper.getResult(statisticTDConditionResp);
//        StatisticPlcMetersResp topPositionsMeasures = topPositionsPlc.stream().filter(x -> x.getEquipmentcode().equals(equipmentData.getCode())).findFirst().orElse(new StatisticPlcMetersResp());
//        double topTrolleyLength = Double.parseDouble(underLength.getRemark() == null ? Constants.OUTCOME : underLength.getRemark());
//        //上小车车位置
//        overlookingHomeResp.setTopTrolley(String.format("%.2f", topPositionsMeasures.getMeasure() != null ? ((positionMeasures.getMeasure() / Constants.CHUNK) / topTrolleyLength) * 100 : 0));
//        //下小车
//        statisticTDConditionResp.setTableName(underResp.getCode());
//        statisticTDConditionResp.setSensorCodes(Arrays.asList(underResp.getRemark().split(",")));
//        statisticTDConditionResp.setStartTime(startDate);
//        statisticTDConditionResp.setEndDateTime(endDate);
//        statisticTDConditionResp.setEqupmentCode(equipmentData.getCode());
//        statisticTDConditionResp.setLimit(limit);
//        //查询plc
//        List<StatisticPlcMetersResp> underPositionsPlc = statisticPlcSensorMapper.getResult(statisticTDConditionResp);
//        StatisticPlcMetersResp underPositionsMeasures = underPositionsPlc.stream().filter(x -> x.getEquipmentcode().equals(equipmentData.getCode())).findFirst().orElse(new StatisticPlcMetersResp());
//        double underTrolleyLength = Double.parseDouble(underLength.getRemark() == null ? Constants.OUTCOME : underLength.getRemark());
//        //上小车车位置
//        //TODO更改
//        overlookingHomeResp.setBelowTrolley(String.format("%.2f", underPositionsMeasures.getMeasure() != null ? ((underPositionsMeasures.getMeasure() / Constants.CHUNK) / underTrolleyLength) * 100 : 0));
//        //设备总重
//        assert equipmentObject != null;
//        overlookingHomeResp.setWeight(equipmentObject.getOperateObject() != null ? equipmentObject.getOperateObject() : String.valueOf(0));
//        //是否在线
//        overlookingHomeResp.setState(!CollectionUtils.isEmpty(underPositionsPlc));
//        //设备编号
//        overlookingHomeResp.setEquipmentCode(equipmentData.getCode());
//        overlookingHomeResp.setLocation(equipmentData.getRemark());
//        overlookingHomeResp.setEquipmentId(equipmentData.getId());
//        return overlookingHomeResp;
//    }


    public EquipmentResp getEquipmentCode(Integer equipmentValue) {
        //获取设备
        List<SysDictionary> equipments = sysDictionaryMapper.selectList(new QueryWrapper<SysDictionary>()
                .lambda()
                .eq(SysDictionary::getParentCode, Constants.CRANE_EQUIPMENT_OBJECT)
                .eq(SysDictionary::getState, Constants.SYS_DICTIONARY_STATE_VALID)
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(SysDictionary::getValue, equipmentValue)
                .orderByDesc(SysDictionary::getValue));
        SysDictionary equipment = equipments.stream().findFirst().orElse(null);
        //获取设备
        BasicsEquipment equipmentData = basicsEquipmentMapper.selectOne(
                new QueryWrapper<BasicsEquipment>()
                        .lambda()
                        .eq(BasicsEquipment::getCode, equipment != null ? equipment.getCode() : Constants.EQUIPMTNTA_CODE)
                        .eq(BasicsEquipment::getIsDelete, Constants.IS_DELETE_NORMAL));
        EquipmentResp equipmentResp = new EquipmentResp();
        BeanHelper.copyProperties(equipmentData, equipmentResp);

        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setOperateObject(equipmentResp.getCode());
        sysDictionaryReq.setParentCode(Constants.EXTERNAL_SOURCES);
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        sysDictionaryReq.setCode(Constants.SINGLE_SCENARIO);
        SysDictionaryResp dic= sysDictionaryMapper.getSingle(sysDictionaryReq);
        equipmentResp.setSingleScenario(dic!=null ? dic.getRemark() : null);
        return equipmentResp;
    }

    public EquipmentExternalLinksResp getOverallScene(){
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        EquipmentExternalLinksResp result = new EquipmentExternalLinksResp();
        sysDictionaryReq.setParentCode(Constants.EXTERNAL_SOURCES);
        sysDictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> dictionaryRespList= sysDictionaryMapper.getList(sysDictionaryReq);
        dictionaryRespList = dictionaryRespList.stream().filter(x->x.getCode().equals(Constants.IFRAME_URL) || x.getCode().equals(Constants.OVERALL_SCENE)).collect(Collectors.toList());
        result.setHost(dictionaryRespList.stream().filter(x->x.getCode().equals(Constants.IFRAME_URL)).findFirst().orElse(new SysDictionaryResp()).getRemark());
        result.setOverallScene(dictionaryRespList.stream().filter(x->x.getCode().equals(Constants.OVERALL_SCENE)).findFirst().orElse(new SysDictionaryResp()).getRemark());
        return result;
    }
}
